package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.*;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Resource
    private RedisClient redisClient;

    /**
     * 根据id查询商户信息
     *
     * @param id
     * @return
     */
    @Override
    public Result queryShopById(Long id) {
        String lockKey = LOCK_SHOP_KEY + id;
        // 1. 缓存空值解决缓存穿透
        Shop shop = redisClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);


        // 2. 互斥锁解决缓存击穿
//         shop = redisClient.queryWithMutex(CACHE_SHOP_KEY, id, Shop.class, lockKey, this::getById, 2L, TimeUnit.SECONDS);

        // 3. 设置逻辑过期时间解决缓存击穿
          shop = redisClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, lockKey, this::getById, 2L, TimeUnit.SECONDS);
        if (shop == null) {
            return Result.fail("商铺不存在！");
        }
        // 7. 返回商户信息
        return Result.ok(shop);
    }

    /**
     * 模拟缓存预热数据
     *
     * @param id      店铺id
     * @param seconds 缓存有效期
     * @throws InterruptedException
     */
    public void saveShop2Redis(Long id, Long seconds) throws InterruptedException {
        // 1. 查询店铺数据
        Shop shop = getById(id);
        // 2. 设置逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(seconds));
        // 3. 写入缓存
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 更新商户信息
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Shop result = getById(shop.getId());
        if (result == null) {
            return Result.fail("商家不存在！");
        }
        // 更新数据库数据
        updateById(shop);
        // 删除缓存数据
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

}
